package com.main.ok;

import java.io.IOException;
import java.io.Writer;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.support.ByteArrayMultipartFileEditor;

@Controller
@RequestMapping("/anno")
public class TestAnnotationController {
    /**
     * 日期类型转换。用到initBinder 自动注册转换器
     * http://localhost:8080/anno/date?start=2012-1-1
     * 
     * @param start
     * @param writer
     */
    @RequestMapping("/date")
    public void testdate(Date start, Writer writer) {
        System.out.println(start);
        try {
            writer.write(start.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public void uploadfile(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        MultipartFile multipartFile = multipartRequest.getFile("file");
        String originalFileName = multipartFile.getOriginalFilename();
        System.out.println(originalFileName);
        try {
            // 设置响应体编码格式
            response.setCharacterEncoding("utf8");
            response.getWriter().println(String.format("you upload file :%s success!! ", originalFileName));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @InitBinder
    private void initBinder(WebDataBinder binder) {
        // 自动把string格式的日期转换为欸date类型
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        format.setLenient(false);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(format, true));
        // 可以把上传的文件直接转换成二进制保存。
        binder.registerCustomEditor(byte[].class, new ByteArrayMultipartFileEditor());
    }

}
